package application;

import java.awt.Toolkit;

import javafx.scene.Node;
import javafx.stage.Stage;

public class DragView {

	private double xOffset = 0;
	private double yOffset = 0;

	private double systemScreenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;// 屏幕的宽
	private double systemScreenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;// 屏幕的高

	private double magneticDistance = 10;

	public DragView(Node node, Stage stage) {
		node.setOnMousePressed(x -> {
			xOffset = x.getSceneX();
			yOffset = x.getSceneY();
		});
		node.setOnMouseDragged(x -> {
			stage.setX(x.getScreenX() - xOffset);
			stage.setY(x.getScreenY() - yOffset);

			glueWall(stage, stage.getX(), stage.getY());
		});

	}

	private void glueWall(Stage stage, double stageX, double stageY) {

		if (stageX < magneticDistance) {
			stage.setX(0);
		} else if (stageY < magneticDistance) {
			stage.setY(0);
		} else if ((stageX + stage.getWidth()) > systemScreenWidth - magneticDistance) {
			stage.setX(systemScreenWidth - stage.getWidth());
		} else if ((stageY + stage.getHeight()) > systemScreenHeight - magneticDistance) {
			stage.setY(systemScreenHeight - stage.getHeight());
		}
	}
}
